package br.edu.ufcg.greengrid.model.machine.state;

import br.edu.ufcg.greengrid.model.job.Job;
import br.edu.ufcg.greengrid.model.machine.Machine;

public class GridMachineState extends AbstractMachineState {

	@Override
	public MSEnum getType() {

		return MSEnum.GRID;
	}

	public void update(Machine m) {

		super.update(m);
		Job job = m.getJob();
		job.update();
	}
	
	@Override
	public void changeStateIfNeeded(Machine m) {
		MSEnum newStateType = null;
		long countdown = 0L;
		
		Job job = m.getJob();
		
		if(isCountdownZero()){
			
			if(job.done()){
				releaseJob(m);
			} else {
				job = cancelJob(m);
				m.canceledJob(job);
			}
			
			newStateType = MSEnum.USER;
			countdown = 0L;
		} else if(job.done()){
			
			releaseJob(m);
			newStateType = MSEnum.IDLE;
			countdown = this.countdown;
		}
		
		
		if(newStateType != null){
			m.changeState(newStateType, countdown);
		}
		
	}
	
	public void run(Machine m, Job nJob) {

		Job cJob = m.getJob();
		if (cJob != null) {
			throw new IllegalStateException(String.format("Machine %s already has a job allocated!", m.getId()));
		}

	}

	public Job cancelJob(Machine m) {
		Job cJob = m.getJob();
		m.setJob(null);
		if (cJob != null) {
			cJob.clear();
		}
		
		return cJob;
	}

	public Job releaseJob(Machine m) {
		Job cJob = m.getJob();
		m.setJob(null);
		return cJob;
	}

}
